package org.edith.shiro.advice;

import org.apache.shiro.authz.UnauthenticatedException;
import org.edith.shiro.enums.ResponseEnum;
import org.edith.shiro.response.CommonResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.core.annotation.Order;
/**
 * 统一异常处理
 */
@ControllerAdvice
@Order(0)
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 无访问权限
     * @return 基础JSON数据
     */
    @ResponseBody
    @ExceptionHandler(value = AuthorizationException.class)
    public CommonResponse authorizationExceptionHandler(){
        return CommonResponse.failure(ResponseEnum.NO_ACCESS);
    }

    /**
     * 用户不存在
     * @return 基础JSON数据
     */
    @ResponseBody
    @ExceptionHandler(value = AuthenticationException.class)
    public CommonResponse authenticationExceptionHandler(){
        return CommonResponse.failure(ResponseEnum.INCORRECT_USERNAME_OR_PASSWORD);
    }

    /**
     * 用户不存在或者密码错误
     * @return 基础JSON数据
     */
    @ResponseBody
    @ExceptionHandler(value = LockedAccountException.class)
    public CommonResponse lockedAccountExceptionHandler(){
        return CommonResponse.failure(ResponseEnum.INCORRECT_USERNAME_OR_PASSWORD);
    }

    /**
     * 用户被锁定
     * @return 基础JSON数据
     */
    @ResponseBody
    @ExceptionHandler(value = IncorrectCredentialsException.class)
    public CommonResponse incorrectCredentialsExceptionHandler(){
        return CommonResponse.failure(ResponseEnum.ACCOUNT_LOCKED);
    }


    /**
     * 用户未登录
     * @return 基础JSON数据
     */
    @ResponseBody
    @ExceptionHandler(value = UnauthenticatedException.class)
    public CommonResponse unauthenticatedExceptionHandler(){
        return CommonResponse.failure(ResponseEnum.NO_LOGIN);
    }

}
